import React from 'react'
import { Form, Input, Button } from 'antd'
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'
import '../style/index.css'

function changePosition(array, sourceIndex, destinationIndex) {
  if (sourceIndex === destinationIndex) return array
  const copyArr = [...array]
  const source = copyArr[sourceIndex]
  copyArr.splice(destinationIndex, 0, source)
  const deleteIndex =
    sourceIndex > destinationIndex ? sourceIndex + 1 : sourceIndex
  copyArr.splice(deleteIndex, 1)
  return copyArr
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 }
  }
}
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 }
  }
}

const DynamicFieldSet = () => {
  const [form] = Form.useForm()

  const onFinish = (values) => {
    console.log('收到表单值：', values)
  }

  function onDragStart(data) {
    console.info('onDragStart', data)
  }

  function onDragUpdate(data) {
    console.info('onDragUpdate', data)
  }

  function onDragEnd(data) {
    console.info('onDragEnd', data)
    const { source, destination } = data
    if (
      source.droppableId === destination.droppableId &&
      source.index !== destination.index
    ) {
      const fieldData = form.getFieldValue(['names'])
      const result = changePosition(fieldData, source.index, destination.index)
      form.setFields([{ name: ['names'], value: result }])
      if (dragDom) {
        dragDom.style.height = 'auto'
      }
    }
  }
  let dragDom: HTMLElement | null = null
  function onBeforeCapture(params) {
    if (dragDom) {
      console.info('onBeforeCapture', params, dragDom, dragDom.offsetHeight)
      dragDom.style.height = dragDom.offsetHeight + 'px'
      // const height = dragDom.
    }

  }

  return (
    <Form
      form={form}
      name="dynamic_form_item"
      {...formItemLayout}
      onFinish={onFinish}
      initialValues={{ names: [1, 2, 3] }}
    >
      <Form.List
        name={['names']}
        rules={[
          // TODO: antd4 Form.List 仅支持自定义规则
          // {
          //   required: true,
          //   message: '必填'
          // },
          // {
          //   validator: async (_, names) => {
          //     console.info(_)
          //     if (!names || names.length < 2) {
          //       return Promise.reject(new Error('至少两名乘客'))
          //     }
          //   }
          // },
          // ({ getFieldValue }) => ({
          //   validator(_, value) {
          //     if (!value || getFieldValue('password') === value) {
          //       return Promise.resolve()
          //     }
          //     return Promise.reject(new Error('您输入的两个密码不匹配！'))
          //   }
          // })
        ]}
      >
        {(fields, { add, remove }) => {
          console.info('fields', fields)
          return (
            <>
              <Form.Item label="乘客">
                <div
                  ref={(dom) => {
                    dragDom = dom
                  }}
                  style={{ display: 'block' }}
                >
                  <DragDropContext
                    onDragEnd={onDragEnd}
                    onBeforeCapture={onBeforeCapture}
                  >
                    <Droppable droppableId="test2">
                      {(provided, snapshot) => {
                        const { innerRef, ...rest } = provided
                        return (
                          <div
                            {...rest}
                            ref={innerRef}
                            style={{ backgroundColor: 'red' }}
                          >
                            {fields.map((field, index) => (
                              <Draggable
                                key={field.key}
                                draggableId={field.fieldKey + ''}
                                index={index}
                              >
                                {(provided) => {
                                  return (
                                    <div
                                      ref={provided.innerRef}
                                      className="clear"
                                      {...provided.draggableProps}
                                      {...provided.dragHandleProps}
                                    >
                                      <Form.Item
                                        required={false}
                                        key={field.key}
                                      >
                                        <Form.Item
                                          {...field}
                                          validateTrigger={['onChange', 'onBlur']}
                                          rules={[
                                            {
                                              required: true,
                                              whitespace: true,
                                              message:
                                              '请输入乘客姓名或删除此字段。'
                                            }
                                          ]}
                                          noStyle
                                        >
                                          <Input
                                            placeholder="乘客姓名"
                                            style={{ width: '60%' }}
                                          />
                                        </Form.Item>
                                        {fields.length > 1 ? (
                                          <MinusCircleOutlined
                                            className="dynamic-delete-button"
                                            style={{ margin: '0 8px' }}
                                            onClick={() => {
                                              remove(field.name)
                                            }}
                                          />
                                        ) : null}
                                      </Form.Item>
                                    </div>
                                  )
                                }}
                              </Draggable>
                            ))}
                          </div>
                        )
                      }}
                    </Droppable>
                  </DragDropContext>
                </div>
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => {
                      add()
                    }}
                    style={{ width: '60%' }}
                  >
                    <PlusOutlined /> 添加字段
                  </Button>
                  <Button
                    type="dashed"
                    onClick={() => {
                      add('表头项', 0)
                    }}
                    style={{ width: '60%', marginTop: '20px' }}
                  >
                    <PlusOutlined /> 在表头添加字段
                  </Button>

                  {/* <Form.ErrorList errors={errors} /> */}
                </Form.Item>
              </Form.Item>
            </>
          )
        }}
      </Form.List>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  )
}

export default DynamicFieldSet
